﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Forms;

namespace PresentationWpf.XMlWorker
{
    public class XMLLoader : XMLWorker
    {
        //Open the XML file, and start to populate the treeview
        public static void populateTreeview(ref Arbore.Arbore arb)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Open XML Document";
            dlg.Filter = "XML Files (*.xml)|*.xml";
         //   dlg.FileName = Application.StartupPath + "\\..\\..\\example.xml";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    

                    //First, we'll load the Xml document
                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(dlg.FileName);
                    Arbore.Nod nod = new Arbore.Nod(xDoc.DocumentElement.Name);
                    arb.AddD(nod);
                    //We make a call to AddNode, where we'll add all of our nodes
                    addTreeNode(xDoc.DocumentElement, ref arb,ref nod);

                   
                  

                }
                catch (XmlException xExc) //Exception is thrown is there is an error in the Xml
                {
                    MessageBox.Show(xExc.Message);
                }
                catch (Exception ex) //General exception
                {
                    MessageBox.Show(ex.Message);
                }
               
            }
        }

        //This function is called recursively until all nodes are loaded
        private static void addTreeNode(XmlNode xmlNode, ref Arbore.Arbore arb,ref Arbore.Nod nod)
        {
            XmlNode xNode;
            
            XmlNodeList xNodeList;
            if (nod != null)
            {
                arb.CurrentNod = nod;
            }
            if (xmlNode.HasChildNodes) //The current node has children
            {
                xNodeList = xmlNode.ChildNodes;

                for (int x = 0; x <= xNodeList.Count - 1; x++) //Loop through the child nodes
                {
                    xNode = xmlNode.ChildNodes[x];
                    var node = new Arbore.Nod(xNode.Name);
                    if (nod != null)
                    {
                        arb.CurrentNod = nod;
                    }
                    arb.AddD(node);
                    node.ParentNode = nod;
                    addTreeNode(xNode,ref arb, ref node);
                }
            }
          
        }
    }
}
